3 -  ‘For' Loops in JS

First for loop

Instead of manually typing inconsole.log five times, we can use afor loop to do this. The aim of this exercise is just to show you how a forloop looks, and demonstrate how useful it is. Subsequent exercises will

a. walk you through the syntax bit by bit
b. explain how the computer thinks as it executes a for loop.

We initially focus on using for loops just to count numbers to keep things simple. But by section 3, we will show you how to do more fancy things!

// Example of a for loop:
for (var counter = 1; counter < 11; counter++) {
    console.log(counter);
}
Starting the for loop

Congratulations! You've just run your firstfor loop. But what you're probably really keen to do is write your own forloop. Below is the general syntax of thefor loop. We want to focus on the first line in the next few exercises.

Syntax

for (var i = 1; i < 11; i = i + 1) {
    /* your code here */;
}

Every for loop makes use of a counting variable. Here, our variable is called i(but it can have any name). The variable has many roles. The first part of the for loop tells the computer to start with a value of 1 for i. It does this by declaring the variable called i and giving it a value of 1.

When the for loop executes the code in the code block—the bit between }—it does so by starting off where i = 1.

// Change where the for loop starts.
for (var i = 5; i < 11; i = i + 1){
    console.log(i);
}
Ending the for loop

We know how to control where the forloop starts. How do we control where it ends? Well, the second part of the forloop determines that.

Syntax

  for (var i = 1; i < 11; i = i + 1) {
        code code code; 
    }
Here, this for loop will keep running until i = 10 ( i.e. while i < 11). So when i = 2, or i = 9, the for loop will run. But once iis no longer less than 11, the loop will stop.
Controlling the for loop

We can now control where the for loop starts and ends. What about controlling what happens in between?

The examples we've looked at have used i = i + 1. This has meant we have incremented (increased) the variable i by 1 each time.

Rules to learn

a. A more efficient way to code to increment up by 1 is to write i++.
b. We decrement down by 1 by writing i--.
c. We can increment up by any value by writing i += x, where x is how much we want to increment up by. e.g.i += 3counts up by 3s.
d. We can decrement down by any value by writing i -= x. (See the Hint for more.)
e. Be very careful with your syntax—if you write a loop that can't properly end, it's called an infinite loop. It will crash your browser!

How does it work?

We've gone through the three bits of syntax for a for loop. But how exactly does it work? Let's imagine the steps the computer takes to run the for loop on the right.

  1. It starts off with i = 2
  2. It then asks: Is i currently less than 13? Because i = 2, this is true and we continue.
  3. We do NOT increment now. Instead, if the condition is met, we run the code block.
  4. Here, the code block prints out the value of i. It is currently 2 so 2 will be printed out.
  5. Once the code block is finished, thefor loop then increments / decrements. Here, we add 1.
  6. Now i = 3. We check if it is less than 13. If it is true, we run the code block.
  7. The code block runs, and then we increment.
  8. We repeat these steps until the condition i < 13 is no longer true.
Practice counting down

for loops only run when the condition istrue.

Do not run the code without changing it!

It is important that there is a way for thefor loop to end. If the for loop is always going to be true, then you will be stuck in an infinite loop and your browser will crash! Look at the code. It is bad.

a. It begins at i = 1
b. It will keep going as long as i >= 1.
c. Because now i = 1, the code will run.

d. We increment i by 1 and now i = 2. This satisfies the condition. We run the code. 
e. Increment i by 1 and now i = 3. This satisfies the condition that i >= 1. We run the code.
f. We will keep incrementing the code up by 1. It will always satisfy the condition. The loop NEVER ends. This will crash your computer!

for (var i = 10; i >= 0; i-=1) {
    console.log(i);
}
Last practice for loop

You have a great handle on for loops now! This will be the last practice one before we look at cool ways to use them.

The next exercise introduces you to arrays. So instead of just counting numbers up and down, we can make the computer do many more interesting things with loops.

Instruction:

Once more, for practice: write a for loop that gets the computer to count down from 100 until 0 by 5. This time, make sure not to print 0.

// Write your very own for loop!
for (var i = 100; i > 0; i-=5){
    console.log(i);
}
Meet arrays

Variables can store numbers or strings. But so far, we've only been able to store ONE number or ONE string. Good thing we have arrays. Arrays:

a. store lists of data
b. can store different data types at the same time
c. are ordered so the position of each piece of data is fixed

Example:

var names = ["Mao","Gandhi","Mandela"];
var sizes = [4, 6, 3, 2, 1, 9];
var mixed = [34, "candy", "blue", 11];

Syntax:
var arrayName = [data, data, data];

Any time you see data surrounded by [ ], it is an array.

// You are now declaring an array.
// Arrays are an awesome data structure!
var junk = ["New Orleans", "Codecademy", 10, 100];
console.log(junk)
Array positions

It's nice that we can put a list of data into an array. But now we need to learn how to get access to the data inside the array.

The position of things in arrays is fixed. So we just need to know the array name (here, it is junkData), and the position of the data we want, and we're done.

Small complication: the position (or the index) of each bit of data is counted starting from 0, not 1.

  1. First element in the array: junkData[0]
  2. Third element in the array: junkData[2]

Arrays have 0-based indexing, so we start counting the positions from 0.

// Practice array!
var junkData = ["Eddie Murphy", 49, "peanuts", 31];
console.log(junkData[3]);
Loops and arrays I

Awesome job! You've now learned about arrays, and how to access one element of the array. But what if there were 100 elements in the array?

For arrays, a useful way to systematically access every element in the array is to use a for loop!

How does it work?

1. Line 3 declares the array. It has 4 elements.
2. We then start the for loop on line 5.
3. We see i starts off at value 0. 
4. The for loop runs until i < 4 (becausecities.length equals 4. The array citieshas 4 elements in it; see the Hint for more.)
5. We will increment i by 1 each time we loop over.
6. We print out cities[0], which is"Melbourne".
7. We then start the loop again. Except nowi = 1
8. It will print out cities[1], which is"Amman"
9. This continues until i is no longer less than cities.length.

  1. Change the elements in the citiesarray. You can put in as many elements as you like.
  2. Run the for loop and see them all printed out!
// Let's print out every element of an array using a for loop
var cities = ["Melbourne", "Amman", "Helsinki", "NYC", "New Orleans", "New York", "Syracuse"];
for (var i = 0; i < cities.length; i++) {
    console.log("I would like to visit " + cities[i]);
}
Loops and arrays II

It's time for you to write your own array and loop over the array. Remember to:

  1. Put commas between each element in the array.
  2. Put semi-colons between each bit of thefor loop.
  3. We suggest you use i as the iterator.
  4. Beware of infinite loops!
  5. Enjoy yourself while smashing through this coding!

  6. Instructions
  7. Create an array called names filled with 5 names.
  8. Write a for loop that prints "I know someone called " followed by names[i]. Make sure there's a space between"called" and the name!
  9. Run your code and the five sentences should print out.
  10. Click "Stuck? Get a hint!" for an example of how to write a for loop.

// Click on "Stuck? Get a hint!" if you get stuck!
var names = ["Bobby", "Susie", "Tom", "William", "Tony"];
for (var i=4; i >= 0; i -= 1){
    console.log("I know someone called", names[i]);
}
Conclusion

You've done an awesome job! Loops are always a little tricky when you first meet them. But they are worth learning because they are really useful.

What now? You have so many useful tricks up your sleeve:

a. if / else statements
b. functions
c. for loops
d. booleans, arrays, variables, etc.